#include <iostream>
#include <string>
#include "mysql.h"
#include <cstdlib>
#include <string>
#include <unistd.h>
#include "comm.hpp"
using namespace std;

bool InsertSql(const string &sql) {
    MYSQL *conn = mysql_init(nullptr);
    mysql_set_character_set(conn, "utf8");
    if (nullptr == mysql_real_connect(conn, "127.0.0.1", "http_test", "12345678", "http_test", 3306, nullptr, 0)) {
        std::cerr << "connect error" << std::endl;
        return 1;
    }
    std::cerr << "connect success" << std::endl;

    // std::cerr << "sql: " << sql << std::endl;
    int ret = mysql_query(conn, sql.c_str());
    // std::cerr << "result: " << ret << std::endl;
    mysql_close(conn);
    return ret == 0 ? true : false;
}

int main() {
    std::string param_string;
    if (GetQueryString(param_string)) {
        std::cerr << "获取参数成功" << std::endl;
        // std::string sql = "insert into user (name, password) values (\'张三\', \'123456\')";
        // 解析数据成为sql格式
        std::string name;
        std::string password;
        CutString(param_string, "&", name, password);
        std::string _name;
        std::string sql_name;
        CutString(name, "=", _name, sql_name);
        std::string _passwd;
        std::string sql_passwd;
        CutString(password, "=", _passwd, sql_passwd);
        std::string sql = "insert into user (name, password) values (\'";
        sql += sql_name;
        sql += "\',\'";
        sql += sql_passwd;
        sql += "\')";
        if (InsertSql(sql)) {
            std::cerr << "insert success" << std::endl;
            std::cout << "<html>";
            std::cout << "<head><meta charset=\"utf-8\"></head>";
            std::cout << "<body><h1>注册成功</h1></body>";
        } else {
            std::cerr << "insert error" << std::endl;
            std::cout << "<html>";
            std::cout << "<head><meta chaeset=\"utf-8\"></head>";
            std::cout << "<body><h1>注册失败</h1></body>";
        }
    } else {
        std::cerr << "获取参数失败" << std::endl;
    }
    return 0;
}
